package com.tanhua.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.service.AdminService;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /*
     *  用户登录验证码图片(获取验证码图片)
     *    请求方式和请求链接 : GET   /verification
     *    请求参数: Query uuid
     *    返回值: 无 直接以流的形式输出
     * */

     @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {

         //随机生成验证码  --使用工具类
         //1.生成一个带有图片的验证码对象(图片数据流,验证码数据)
         LineCaptcha captcha = CaptchaUtil.createLineCaptcha(299, 97);//指定图片的长度和宽度

         //2.将验证码数据存入redis中
         String code = captcha.getCode();
         redisTemplate.opsForValue().set(Constants.CAP_CODE+uuid,code);
         //3,以数据流响应
         captcha.write(response.getOutputStream()); //将图片数据写入响应的输入流中

     }

    /*
     *  用户登录
     *    请求方式和请求链接 : POST   /login
     *    请求参数:Body username,password,verificationCode,uuid
     *    返回值: token
     * */

    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");


        Map retMap= adminService.login(username,password,verificationCode,uuid);

       return ResponseEntity.ok(retMap);
    }

    /*
     * 用户基本信息
     *    请求方式和请求链接 : POST  /profile
     *    请求参数: Authorization
     *    返回值: AdminVo
     * */

    @PostMapping("/profile")
    public ResponseEntity profile(){

        Admin admin = adminService.profile(AdminHolder.getUserId());
        AdminVo vo = AdminVo.init(admin);

        return ResponseEntity.ok(vo);
    }


}
